package com.dc.base.controller;

import com.dc.base.exception.BusinessException;
import com.dc.base.exception.ResponseCode;
import org.apache.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.Response;
import java.sql.SQLException;

/**
 * @author Enzo
 * @Description TODO
 * @date 2018-11-12 15:47
 */
@Controller
@ResponseBody
public class BaseController {
    private Logger log = Logger.getLogger(BaseController.class);
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @InitBinder
    public void initHttpParams(HttpServletRequest req, HttpServletResponse res) {
        request = req;
        response = res;
        session = req.getSession();
    }

    @ExceptionHandler(Exception.class)
    public BusinessException exception(Exception e){
        BusinessException be = new BusinessException(ResponseCode.SYS_ERROR.getCode(),ResponseCode.SYS_ERROR.getMessage());
        be.setStackTrace(e.getStackTrace());
        response.setStatus(ResponseCode.SYS_ERROR.getCode());
        return be;
    }

    @ExceptionHandler(BusinessException.class)
    public BusinessException businessException(BusinessException ex){
        response.setStatus(ex.getCode());
        return ex;
    }

    @ExceptionHandler(SQLException.class)
    public  BusinessException SQLException(SQLException e) {
        BusinessException ex = new BusinessException(ResponseCode.SQL_ERROR.getCode(), ResponseCode.SQL_ERROR.getMessage());
        ex.setStackTrace(e.getStackTrace());
        return businessException(ex);
    }
}
